import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import router from '@/router';
import { jwtDecode } from 'jwt-decode';

// 扩展接口
interface JwtPayload {
  user: any;
}




export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})



export const loginStatus = defineStore('login', () => {
  const isLogin = ref(false);
  const token = ref("");
  const nickname = ref("");
  const userId = ref("");
  const avatarUrl = ref("");
  const account = ref("");
  const isAdmin = ref(0);

  type userType = {
    account: string, admin: number, avatar: string, id: string, nickname: string
  };

  function setup(user: userType) {
    isLogin.value = true;
    token.value = localStorage.getItem('token') as string;
    nickname.value = user.nickname;
    userId.value = user.id;
    avatarUrl.value = user.avatar;
    account.value = user.account;
    isAdmin.value = user.admin;
  }
  function setupUser(data: { name: string, nickname: string }) {
    isLogin.value = true;
  }
  function setupToken(token: string) {
    localStorage.setItem('token', token);
  }


  // 调起初始化
  // login(localStorage.getItem('token') as string);

  function login(data: any, route: boolean = true): void {

    const user: userType = {
      account: data.name,
      admin: 0,
      avatar: data.avatar,
      nickname: data.nickname,
      id: data.id,
    }

    console.log(user);

    setup(user);

    // 路由
    if (route) {
      router.push({ name: 'home' });
    }
  }

  function logout() {
    localStorage.removeItem('token')
    isLogin.value = false;
    router.push({ name: 'home' });
  }

  function checkLogin(): boolean {
    console.log(isLogin.value);

    return isLogin.value;
  }


  return { isLogin, nickname, avatarUrl, account, userId, token, isAdmin, login, logout, checkLogin, setupToken }
})
